# -*- coding: utf-8 -*- 
from flask import Blueprint, request
from sms.database import db_session, Sms
from sms.util import Result
from sms import app
import datetime
import logging, json
import hashlib
from yunpian_python_sdk.model import constant as YC
from yunpian_python_sdk.ypclient import YunpianClient
from apscheduler.schedulers.background import  BackgroundScheduler
import time
import random

# 初始化client,apikey作为所有请求的默认值

logger = logging.getLogger('SMS')
session = db_session()
APIKEY = app.config['API_KEY']

mod = Blueprint('general',__name__)

#短信发送模板
def sched_sms(mobile,message,createTime):
    
        
    try:
        #云片网提供发送短信客户端接口
        clnt = YunpianClient(APIKEY)
        param = {YC.MOBILE:mobile,YC.TEXT:message}
        r = clnt.sms().batch_send(param)
        # 获取返回结果, 返回码:r.code(),返回码描述:r.msg(),API结果:r.data(),其他说明:r.detail(),调用异常:r.exception()
        # 短信:clnt.sms() 账户:clnt.user() 签名:clnt.sign() 模版:clnt.tpl() 语音:clnt.voice() 流量:clnt.flow()
        result = r.code()
        ms = r.msg()
        data = r.data()	
       # if ms == None :
#
        #    result = 500
        #    return result

        sendTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        delaySeconds = None
        
        logger.info('Get request of sending message to mobile {0}, content {1}, schedule_time {2} from {3},{4},{5},{6}'.format(mobile,message,createTime,sendTime,delaySeconds,result,data))

        mobiles = mobile.split(",")
        
        for m in mobiles:
        
            sms = Sms(None,str(m),message,createTime,sendTime,delaySeconds,result)
        
            session.add(sms)
            
        session.commit()
    except Exception as e:
    
        print("发生的异常是： ",e)  
        return "failed"
    return result

#通知类型短信发送接口
@mod.route('/send-sms', methods=[ 'POST'])
def send_sms(mobiles=None,content=None):
    global time
    result = 0
    scheduler = BackgroundScheduler()
    
    createTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  
    
    try:
        args = request.get_data()
        arg = json.loads(args)

        client = None
        time_t = arg['time']
        mobiles = arg["mobiles"]
        content = arg["message"]


        t = int(time_t)  #定时任务时间（秒）
        
        tt = time.time()  #获取当前时间戳
        if t >0:

            d = datetime.datetime.fromtimestamp(tt+t)
            date = str(d)

#    如果需要定时发送，只要把time+datetime().format(2018-04-18 15:45:00)再赋值给run_date
            scheduler.add_job(sched_sms, 'date', run_date=date[:-7],args=(mobiles,content,createTime))
            scheduler.start()
            result = 0                              
        else:              
               
            #logger.info("发生了什么呢？".format(result))
            result = sched_sms(mobiles,content,createTime)
            
        logger.info("发生了什么呢？".format(result))
        back_data = {"code":result}

    except Exception as e:
        
        print("......",e)
        logger.info("发生的异常是: ".format(e))
        return '400'

        
    return json.dumps(back_data)




#发送一个四位数字的验证码
@mod.route('/send-verify-code', methods=['GET', 'POST'])
def verify_code():
    
    args = request.get_data()
    arg = json.loads(args)
    
    mobile = arg["mobile"]
    
    createTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    salt = "edoomath"
    chars=['0','1','2','3','4','5','6','7','8','9'] 
    x = random.choice(chars),random.choice(chars),random.choice(chars),random.choice(chars) 
    verifyCode = "".join(x) 
    
    pvcode = verifyCode+mobile+salt
    
    s = hashlib.sha256()
    
    s.update(pvcode.encode("utf8"))
    
    token = s.hexdigest()
    #content模板可以从数据库获取。测试先用这个。
    content = "【陆老师小课堂】您的验证码是%s" %verifyCode

    result = sched_sms(mobile,content,createTime)
    
    back_data = {"code":result,"message":content,"data":{"token":str(token)}}

    return json.dumps(back_data)

